package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

type UpdateContentRequest struct {
	Id      int    `json:"id"`
	Content string `json:"content"`
}

type Response struct {
	Code      int         `json:"code"`
	Message   string      `json:"message"`
	Data      interface{} `json:"data"`
	Timestamp string      `json:"timestamp"`
}

func main() {
	fmt.Println("测试 PUT /api/v1/content 接口错误处理...")

	// 测试不存在的ID
	req := UpdateContentRequest{
		Id:      999, // 使用不存在的ID
		Content: "# 测试内容\n\n这是测试内容",
	}

	// 转换为JSON
	jsonData, err := json.Marshal(req)
	if err != nil {
		fmt.Printf("JSON序列化失败: %v\n", err)
		return
	}

	fmt.Printf("发送请求数据: %s\n", string(jsonData))

	// 发送PUT请求
	resp, err := http.NewRequest("PUT", "http://localhost:8080/api/v1/content", bytes.NewBuffer(jsonData))
	if err != nil {
		fmt.Printf("创建请求失败: %v\n", err)
		return
	}

	resp.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 10 * time.Second}
	response, err := client.Do(resp)
	if err != nil {
		fmt.Printf("发送请求失败: %v\n", err)
		return
	}
	defer response.Body.Close()

	// 读取响应
	body, err := io.ReadAll(response.Body)
	if err != nil {
		fmt.Printf("读取响应失败: %v\n", err)
		return
	}

	fmt.Printf("响应状态码: %d\n", response.StatusCode)
	fmt.Printf("响应内容: %s\n", string(body))

	// 解析响应
	var apiResp Response
	err = json.Unmarshal(body, &apiResp)
	if err != nil {
		fmt.Printf("解析响应失败: %v\n", err)
		return
	}

	if response.StatusCode == 404 && apiResp.Code == 404 {
		fmt.Println("✅ 错误处理正确: 返回404状态码")
	} else {
		fmt.Printf("❌ 错误处理异常: 期望404，实际%d\n", response.StatusCode)
	}

	// 测试空内容
	fmt.Println("\n测试空内容...")
	req2 := UpdateContentRequest{
		Id:      7,
		Content: "", // 空内容
	}

	jsonData2, _ := json.Marshal(req2)
	fmt.Printf("发送请求数据: %s\n", string(jsonData2))

	resp2, _ := http.NewRequest("PUT", "http://localhost:8080/api/v1/content", bytes.NewBuffer(jsonData2))
	resp2.Header.Set("Content-Type", "application/json")

	response2, err := client.Do(resp2)
	if err != nil {
		fmt.Printf("发送请求失败: %v\n", err)
		return
	}
	defer response2.Body.Close()

	body2, _ := io.ReadAll(response2.Body)
	fmt.Printf("响应状态码: %d\n", response2.StatusCode)
	fmt.Printf("响应内容: %s\n", string(body2))

	if response2.StatusCode == 400 {
		fmt.Println("✅ 空内容验证正确: 返回400状态码")
	} else {
		fmt.Printf("❌ 空内容验证异常: 期望400，实际%d\n", response2.StatusCode)
	}
}